<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">宿舍申请</h1>
          <p class="mt-1 text-sm text-gray-600">选择宿舍楼、房间和室友，提交住宿申请</p>
        </div>
        <div class="flex items-center gap-3">
          <button
            @click="showApplicationHistory = true"
            class="inline-flex items-center px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <ClockIcon class="w-4 h-4 mr-2" />
            申请记录
          </button>
          <button
            @click="refreshData"
            class="inline-flex items-center px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
          >
            <ArrowPathIcon class="w-4 h-4 mr-2" />
            刷新
          </button>
        </div>
      </div>
    </div>

    <!-- 申请状态提示 -->
    <div v-if="applicationStatus" class="mb-6">
      <div :class="[
        'rounded-lg p-4 border',
        applicationStatus.type === 'pending' ? 'bg-yellow-50 border-yellow-200' :
        applicationStatus.type === 'approved' ? 'bg-green-50 border-green-200' :
        applicationStatus.type === 'rejected' ? 'bg-red-50 border-red-200' :
        'bg-blue-50 border-blue-200'
      ]">
        <div class="flex items-start">
          <div class="flex-shrink-0">
            <InformationCircleIcon :class="[
              'w-5 h-5',
              applicationStatus.type === 'pending' ? 'text-yellow-600' :
              applicationStatus.type === 'approved' ? 'text-green-600' :
              applicationStatus.type === 'rejected' ? 'text-red-600' :
              'text-blue-600'
            ]" />
          </div>
          <div class="ml-3">
            <h3 :class="[
              'text-sm font-medium',
              applicationStatus.type === 'pending' ? 'text-yellow-800' :
              applicationStatus.type === 'approved' ? 'text-green-800' :
              applicationStatus.type === 'rejected' ? 'text-red-800' :
              'text-blue-800'
            ]">
              {{ applicationStatus.title }}
            </h3>
            <p :class="[
              'mt-1 text-sm',
              applicationStatus.type === 'pending' ? 'text-yellow-700' :
              applicationStatus.type === 'approved' ? 'text-green-700' :
              applicationStatus.type === 'rejected' ? 'text-red-700' :
              'text-blue-700'
            ]">
              {{ applicationStatus.message }}
            </p>
            <p v-if="applicationStatus.submittedAt" :class="[
              'mt-1 text-xs',
              applicationStatus.type === 'pending' ? 'text-yellow-600' :
              applicationStatus.type === 'approved' ? 'text-green-600' :
              applicationStatus.type === 'rejected' ? 'text-red-600' :
              'text-blue-600'
            ]">
              申请时间：{{ formatDateTime(applicationStatus.submittedAt) }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 申请步骤 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 mb-6 p-6">
      <div class="flex items-center justify-between">
        <div v-for="(step, index) in steps" :key="step.id" class="flex items-center">
          <div class="flex items-center">
            <div :class="[
              'w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium',
              currentStep >= step.id ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-600'
            ]">
              {{ step.id }}
            </div>
            <div class="ml-3">
              <p :class="[
                'text-sm font-medium',
                currentStep >= step.id ? 'text-blue-600' : 'text-gray-500'
              ]">
                {{ step.title }}
              </p>
              <p class="text-xs text-gray-500">{{ step.description }}</p>
            </div>
          </div>
          <div v-if="index < steps.length - 1" :class="[
            'w-16 h-0.5 mx-4',
            currentStep > step.id ? 'bg-blue-600' : 'bg-gray-200'
          ]"></div>
        </div>
      </div>
    </div>

    <!-- 步骤1：选择宿舍楼 -->
    <div v-if="currentStep === 1" class="space-y-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 class="text-lg font-medium text-gray-900 mb-4">选择宿舍楼</h2>
        
        <!-- 筛选条件 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">性别要求</label>
            <select
              v-model="filters.gender"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            >
              <option value="">全部</option>
              <option value="男">男生宿舍</option>
              <option value="女">女生宿舍</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">楼层偏好</label>
            <select
              v-model="filters.floor"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            >
              <option value="">无偏好</option>
              <option value="low">低楼层(1-3层)</option>
              <option value="middle">中楼层(4-6层)</option>
              <option value="high">高楼层(7层以上)</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">设施要求</label>
            <select
              v-model="filters.facility"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            >
              <option value="">无要求</option>
              <option value="ac">空调</option>
              <option value="elevator">电梯</option>
              <option value="wifi">WiFi</option>
            </select>
          </div>
        </div>
        
        <!-- 宿舍楼列表 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div v-for="building in filteredBuildings" :key="building.id" 
               @click="selectBuilding(building)"
               :class="[
                 'border rounded-lg p-4 cursor-pointer transition-all hover:shadow-md',
                 selectedBuilding?.id === building.id ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'
               ]">
            <div class="flex items-start justify-between mb-3">
              <div>
                <h3 class="text-lg font-medium text-gray-900">{{ building.name }}</h3>
                <p class="text-sm text-gray-500">{{ building.description }}</p>
              </div>
              <span :class="[
                'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                building.gender === '男' ? 'bg-blue-100 text-blue-800' : 'bg-pink-100 text-pink-800'
              ]">
                {{ building.gender }}生宿舍
              </span>
            </div>
            
            <div class="space-y-2">
              <div class="flex items-center justify-between text-sm">
                <span class="text-gray-600">总房间数：</span>
                <span class="font-medium">{{ building.totalRooms }}</span>
              </div>
              <div class="flex items-center justify-between text-sm">
                <span class="text-gray-600">可用房间：</span>
                <span :class="[
                  'font-medium',
                  building.availableRooms > 0 ? 'text-green-600' : 'text-red-600'
                ]">{{ building.availableRooms }}</span>
              </div>
              <div class="flex items-center justify-between text-sm">
                <span class="text-gray-600">楼层数：</span>
                <span class="font-medium">{{ building.floors }}层</span>
              </div>
            </div>
            
            <div class="mt-3 pt-3 border-t border-gray-200">
              <div class="flex items-center justify-between">
                <div class="flex flex-wrap gap-1">
                  <span v-for="facility in building.facilities" :key="facility"
                        class="inline-flex items-center px-2 py-1 rounded text-xs bg-gray-100 text-gray-700">
                    {{ facility }}
                  </span>
                </div>
                <button
                  @click="showBuildingDetail(building)"
                  class="text-xs text-blue-600 hover:text-blue-900 transition-colors"
                >
                  查看详情
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 步骤2：选择房间 -->
    <div v-if="currentStep === 2" class="space-y-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-medium text-gray-900">选择房间 - {{ selectedBuilding?.name }}</h2>
          <button
            @click="currentStep = 1"
            class="text-sm text-blue-600 hover:text-blue-900 transition-colors"
          >
            重新选择宿舍楼
          </button>
        </div>
        
        <!-- 楼层选择 -->
        <div class="mb-6">
          <label class="block text-sm font-medium text-gray-700 mb-2">选择楼层</label>
          <div class="flex flex-wrap gap-2">
            <button v-for="floor in selectedBuilding?.floors" :key="floor"
                    @click="selectedFloor = floor"
                    :class="[
                      'px-3 py-2 text-sm font-medium rounded-lg transition-colors',
                      selectedFloor === floor ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    ]">
              {{ floor }}层
            </button>
          </div>
        </div>
        
        <!-- 房间列表 -->
        <div v-if="selectedFloor" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div v-for="room in getFloorRooms(selectedFloor)" :key="room.id"
               @click="selectRoom(room)"
               :class="[
                 'border rounded-lg p-4 cursor-pointer transition-all',
                 room.status === 'available' ? 'border-green-200 bg-green-50 hover:bg-green-100' :
                 room.status === 'partial' ? 'border-yellow-200 bg-yellow-50 hover:bg-yellow-100' :
                 'border-gray-200 bg-gray-50 cursor-not-allowed',
                 selectedRoom?.id === room.id ? 'ring-2 ring-blue-500' : ''
               ]">
            <div class="flex items-center justify-between mb-2">
              <h3 class="font-medium text-gray-900">{{ room.number }}</h3>
              <span :class="[
                'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                room.status === 'available' ? 'bg-green-100 text-green-800' :
                room.status === 'partial' ? 'bg-yellow-100 text-yellow-800' :
                'bg-gray-100 text-gray-800'
              ]">
                {{ getStatusText(room.status) }}
              </span>
            </div>
            
            <div class="space-y-1 text-sm text-gray-600">
              <div class="flex justify-between">
                <span>床位：</span>
                <span>{{ room.occupiedBeds }}/{{ room.totalBeds }}</span>
              </div>
              <div class="flex justify-between">
                <span>朝向：</span>
                <span>{{ room.orientation }}</span>
              </div>
              <div class="flex justify-between">
                <span>面积：</span>
                <span>{{ room.area }}㎡</span>
              </div>
            </div>
            
            <div v-if="room.facilities" class="mt-2 pt-2 border-t border-gray-200">
              <div class="flex flex-wrap gap-1">
                <span v-for="facility in room.facilities" :key="facility"
                      class="inline-flex items-center px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-600">
                  {{ facility }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 步骤3：选择室友 -->
    <div v-if="currentStep === 3" class="space-y-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-medium text-gray-900">选择室友 - {{ selectedRoom?.number }}</h2>
          <button
            @click="currentStep = 2"
            class="text-sm text-blue-600 hover:text-blue-900 transition-colors"
          >
            重新选择房间
          </button>
        </div>
        
        <!-- 当前室友 -->
        <div v-if="currentRoommates.length > 0" class="mb-6">
          <h3 class="text-md font-medium text-gray-900 mb-3">当前室友</h3>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div v-for="roommate in currentRoommates" :key="roommate.id"
                 class="border border-gray-200 rounded-lg p-4">
              <div class="flex items-center space-x-3">
                <div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center overflow-hidden">
                  <img v-if="roommate.avatar" :src="roommate.avatar" :alt="roommate.name" class="w-full h-full object-cover" />
                  <UserIcon v-else class="w-5 h-5 text-gray-400" />
                </div>
                <div>
                  <p class="font-medium text-gray-900">{{ roommate.name }}</p>
                  <p class="text-sm text-gray-500">{{ roommate.studentId }} · {{ roommate.major }}</p>
                </div>
              </div>
              <div class="mt-3 text-sm text-gray-600">
                <p>年级：{{ roommate.grade }}</p>
                <p>兴趣：{{ roommate.hobbies || '暂无' }}</p>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 可选室友 -->
        <div v-if="availableRoommates.length > 0">
          <h3 class="text-md font-medium text-gray-900 mb-3">可选室友</h3>
          <div class="mb-4">
            <div class="relative">
              <input
                v-model="roommateSearch"
                type="text"
                placeholder="搜索姓名或学号..."
                class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
              <MagnifyingGlassIcon class="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
            </div>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div v-for="candidate in filteredRoommates" :key="candidate.id"
                 @click="toggleRoommateSelection(candidate)"
                 :class="[
                   'border rounded-lg p-4 cursor-pointer transition-all hover:shadow-sm',
                   selectedRoommates.includes(candidate.id) ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300'
                 ]">
              <div class="flex items-center space-x-3">
                <div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center overflow-hidden">
                  <img v-if="candidate.avatar" :src="candidate.avatar" :alt="candidate.name" class="w-full h-full object-cover" />
                  <UserIcon v-else class="w-5 h-5 text-gray-400" />
                </div>
                <div class="flex-1">
                  <p class="font-medium text-gray-900">{{ candidate.name }}</p>
                  <p class="text-sm text-gray-500">{{ candidate.studentId }} · {{ candidate.major }}</p>
                </div>
                <div v-if="selectedRoommates.includes(candidate.id)" class="text-blue-600">
                  <CheckIcon class="w-5 h-5" />
                </div>
              </div>
              <div class="mt-3 text-sm text-gray-600">
                <p>年级：{{ candidate.grade }}</p>
                <p>兴趣：{{ candidate.hobbies || '暂无' }}</p>
                <p>作息：{{ candidate.schedule || '暂无' }}</p>
              </div>
            </div>
          </div>
        </div>
        
        <div v-if="availableRoommates.length === 0" class="text-center py-8">
          <UserGroupIcon class="w-12 h-12 text-gray-400 mx-auto mb-3" />
          <p class="text-gray-500">暂无可选室友</p>
        </div>
      </div>
    </div>

    <!-- 步骤4：确认申请 -->
    <div v-if="currentStep === 4" class="space-y-6">
      <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 class="text-lg font-medium text-gray-900 mb-6">确认申请信息</h2>
        
        <div class="space-y-6">
          <!-- 宿舍信息 -->
          <div>
            <h3 class="text-md font-medium text-gray-900 mb-3">宿舍信息</h3>
            <div class="bg-gray-50 rounded-lg p-4">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700">宿舍楼</label>
                  <p class="mt-1 text-sm text-gray-900">{{ selectedBuilding?.name }}</p>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700">房间号</label>
                  <p class="mt-1 text-sm text-gray-900">{{ selectedRoom?.number }}</p>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700">楼层</label>
                  <p class="mt-1 text-sm text-gray-900">{{ selectedFloor }}层</p>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700">朝向</label>
                  <p class="mt-1 text-sm text-gray-900">{{ selectedRoom?.orientation }}</p>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 室友信息 -->
          <div v-if="selectedRoommateDetails.length > 0">
            <h3 class="text-md font-medium text-gray-900 mb-3">选择的室友</h3>
            <div class="bg-gray-50 rounded-lg p-4">
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div v-for="roommate in selectedRoommateDetails" :key="roommate.id"
                     class="flex items-center space-x-3">
                  <div class="w-8 h-8 bg-gray-200 rounded-full flex items-center justify-center overflow-hidden">
                    <img v-if="roommate.avatar" :src="roommate.avatar" :alt="roommate.name" class="w-full h-full object-cover" />
                    <UserIcon v-else class="w-4 h-4 text-gray-400" />
                  </div>
                  <div>
                    <p class="text-sm font-medium text-gray-900">{{ roommate.name }}</p>
                    <p class="text-xs text-gray-500">{{ roommate.studentId }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 申请说明 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">申请说明（可选）</label>
            <textarea
              v-model="applicationNote"
              rows="3"
              placeholder="请输入申请说明或特殊要求..."
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
            ></textarea>
          </div>
          
          <!-- 协议确认 -->
          <div class="flex items-start space-x-3">
            <input
              v-model="agreeTerms"
              type="checkbox"
              class="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <div class="text-sm">
              <label class="font-medium text-gray-700">我已阅读并同意</label>
              <button class="text-blue-600 hover:text-blue-900 ml-1">《宿舍管理规定》</button>
              <span class="text-gray-700">和</span>
              <button class="text-blue-600 hover:text-blue-900 ml-1">《住宿协议》</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="flex justify-between">
      <button
        v-if="currentStep > 1"
        @click="currentStep--"
        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
      >
        上一步
      </button>
      <div v-else></div>
      
      <div class="flex gap-3">
        <button
          v-if="currentStep < 4"
          @click="nextStep"
          :disabled="!canProceed"
          class="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          下一步
        </button>
        <button
          v-if="currentStep === 4"
          @click="submitApplication"
          :disabled="!canSubmit"
          class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          提交申请
        </button>
      </div>
    </div>

    <!-- 申请历史记录弹窗 -->
    <div v-if="showApplicationHistory" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[80vh] overflow-hidden">
        <div class="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 class="text-lg font-medium text-gray-900">申请历史记录</h2>
          <button
            @click="showApplicationHistory = false"
            class="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <XMarkIcon class="w-6 h-6" />
          </button>
        </div>
        <div class="p-6 overflow-y-auto max-h-[60vh]">
          <div v-if="applicationHistory.length === 0" class="text-center py-8">
            <ClockIcon class="w-12 h-12 text-gray-400 mx-auto mb-3" />
            <p class="text-gray-500">暂无申请记录</p>
          </div>
          <div v-else class="space-y-4">
            <div v-for="record in applicationHistory" :key="record.id"
                 class="border border-gray-200 rounded-lg p-4">
              <div class="flex items-center justify-between mb-3">
                <div class="flex items-center space-x-3">
                  <span :class="[
                    'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                    record.status === 'pending' ? 'bg-yellow-100 text-yellow-800' :
                    record.status === 'approved' ? 'bg-green-100 text-green-800' :
                    record.status === 'rejected' ? 'bg-red-100 text-red-800' :
                    'bg-gray-100 text-gray-800'
                  ]">
                    {{ getApplicationStatusText(record.status) }}
                  </span>
                  <span class="text-sm text-gray-500">{{ formatDateTime(record.submittedAt) }}</span>
                </div>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
                <div>
                  <span class="text-gray-600">宿舍楼：</span>
                  <span class="font-medium">{{ record.buildingName }}</span>
                </div>
                <div>
                  <span class="text-gray-600">房间号：</span>
                  <span class="font-medium">{{ record.roomNumber }}</span>
                </div>
                <div>
                  <span class="text-gray-600">申请类型：</span>
                  <span class="font-medium">{{ record.applicationType }}</span>
                </div>
              </div>
              <div v-if="record.note" class="mt-3 text-sm text-gray-600">
                <span class="font-medium">申请说明：</span>{{ record.note }}
              </div>
              <div v-if="record.rejectReason" class="mt-3 text-sm text-red-600">
                <span class="font-medium">拒绝原因：</span>{{ record.rejectReason }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 宿舍详情弹窗 -->
    <div v-if="showBuildingDetailModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[80vh] overflow-hidden">
        <div class="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 class="text-lg font-medium text-gray-900">{{ selectedBuildingDetail?.name }} - 详细信息</h2>
          <button
            @click="showBuildingDetailModal = false"
            class="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <XMarkIcon class="w-6 h-6" />
          </button>
        </div>
        <div class="p-6 overflow-y-auto max-h-[60vh]">
          <div v-if="selectedBuildingDetail" class="space-y-6">
            <!-- 基本信息 -->
            <div>
              <h3 class="text-md font-medium text-gray-900 mb-3">基本信息</h3>
              <div class="bg-gray-50 rounded-lg p-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700">宿舍楼名称</label>
                    <p class="mt-1 text-sm text-gray-900">{{ selectedBuildingDetail.name }}</p>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700">性别要求</label>
                    <p class="mt-1 text-sm text-gray-900">{{ selectedBuildingDetail.gender }}生宿舍</p>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700">总楼层</label>
                    <p class="mt-1 text-sm text-gray-900">{{ selectedBuildingDetail.floors }}层</p>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700">房间总数</label>
                    <p class="mt-1 text-sm text-gray-900">{{ selectedBuildingDetail.totalRooms }}间</p>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700">可用房间</label>
                    <p class="mt-1 text-sm text-gray-900">{{ selectedBuildingDetail.availableRooms }}间</p>
                  </div>
                  <div>
                    <label class="block text-sm font-medium text-gray-700">入住率</label>
                    <p class="mt-1 text-sm text-gray-900">{{ Math.round((selectedBuildingDetail.totalRooms - selectedBuildingDetail.availableRooms) / selectedBuildingDetail.totalRooms * 100) }}%</p>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 设施信息 -->
            <div>
              <h3 class="text-md font-medium text-gray-900 mb-3">设施配置</h3>
              <div class="bg-gray-50 rounded-lg p-4">
                <div class="flex flex-wrap gap-2">
                  <span v-for="facility in selectedBuildingDetail.facilities" :key="facility"
                        class="inline-flex items-center px-3 py-1 rounded-full text-sm bg-blue-100 text-blue-800">
                    {{ facility }}
                  </span>
                </div>
              </div>
            </div>
            
            <!-- 位置信息 -->
            <div>
              <h3 class="text-md font-medium text-gray-900 mb-3">位置描述</h3>
              <div class="bg-gray-50 rounded-lg p-4">
                <p class="text-sm text-gray-700">{{ selectedBuildingDetail.description }}</p>
              </div>
            </div>
            
            <!-- 管理规定 -->
            <div>
              <h3 class="text-md font-medium text-gray-900 mb-3">管理规定</h3>
              <div class="bg-gray-50 rounded-lg p-4">
                <ul class="text-sm text-gray-700 space-y-1">
                  <li>• 严禁在宿舍内使用大功率电器</li>
                  <li>• 保持宿舍清洁卫生，定期打扫</li>
                  <li>• 遵守作息时间，晚上11点后保持安静</li>
                  <li>• 不得私自调换床位或房间</li>
                  <li>• 爱护公共设施，损坏照价赔偿</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../../stores/app'
import {
  ArrowPathIcon,
  InformationCircleIcon,
  UserIcon,
  UserGroupIcon,
  MagnifyingGlassIcon,
  CheckIcon,
  ClockIcon,
  XMarkIcon
} from '@heroicons/vue/24/outline'

// 使用stores
const appStore = useAppStore()

// 响应式数据
const currentStep = ref(1)
const selectedBuilding = ref(null)
const selectedFloor = ref(null)
const selectedRoom = ref(null)
const selectedRoommates = ref([])
const applicationNote = ref('')
const agreeTerms = ref(false)
const roommateSearch = ref('')
const showApplicationHistory = ref(false)
const showBuildingDetailModal = ref(false)
const selectedBuildingDetail = ref(null)

const filters = ref({
  gender: '',
  floor: '',
  facility: ''
})

const buildings = ref([])
const rooms = ref([])
const availableRoommates = ref([])
const currentRoommates = ref([])
const applicationStatus = ref(null)
const applicationHistory = ref([])

// 步骤配置
const steps = [
  { id: 1, title: '选择宿舍楼', description: '选择合适的宿舍楼' },
  { id: 2, title: '选择房间', description: '选择具体房间' },
  { id: 3, title: '选择室友', description: '选择室友（可选）' },
  { id: 4, title: '确认申请', description: '确认信息并提交' }
]

// 计算属性
const filteredBuildings = computed(() => {
  let filtered = buildings.value
  
  if (filters.value.gender) {
    filtered = filtered.filter(building => building.gender === filters.value.gender)
  }
  
  return filtered
})

const filteredRoommates = computed(() => {
  let filtered = availableRoommates.value
  
  if (roommateSearch.value) {
    const search = roommateSearch.value.toLowerCase()
    filtered = filtered.filter(roommate => 
      roommate.name.toLowerCase().includes(search) ||
      roommate.studentId.toLowerCase().includes(search)
    )
  }
  
  return filtered
})

const selectedRoommateDetails = computed(() => {
  return availableRoommates.value.filter(roommate => 
    selectedRoommates.value.includes(roommate.id)
  )
})

const canProceed = computed(() => {
  switch (currentStep.value) {
    case 1:
      return selectedBuilding.value !== null
    case 2:
      return selectedRoom.value !== null
    case 3:
      return true // 室友选择是可选的
    default:
      return false
  }
})

const canSubmit = computed(() => {
  return agreeTerms.value && selectedBuilding.value && selectedRoom.value
})

// 方法
const refreshData = async () => {
  try {
    await Promise.all([
      loadBuildings(),
      loadApplicationStatus()
    ])
    appStore.showNotification('数据刷新成功', 'success')
  } catch (error) {
    appStore.showNotification('刷新失败，请重试', 'error')
  }
}

const loadBuildings = async () => {
  // 模拟加载宿舍楼数据
  buildings.value = [
    {
      id: 1,
      name: '1号宿舍楼',
      description: '靠近教学楼，交通便利',
      gender: '男',
      totalRooms: 120,
      availableRooms: 15,
      floors: 6,
      facilities: ['空调', '热水器', '洗衣机', 'WiFi']
    },
    {
      id: 2,
      name: '2号宿舍楼',
      description: '环境优美，设施完善',
      gender: '女',
      totalRooms: 100,
      availableRooms: 8,
      floors: 5,
      facilities: ['空调', '热水器', '洗衣机', 'WiFi', '电梯']
    },
    {
      id: 3,
      name: '3号宿舍楼',
      description: '新建宿舍，设施先进',
      gender: '男',
      totalRooms: 150,
      availableRooms: 25,
      floors: 8,
      facilities: ['空调', '热水器', '洗衣机', 'WiFi', '电梯', '健身房']
    },
    {
      id: 4,
      name: '4号宿舍楼',
      description: '靠近图书馆，学习氛围浓厚',
      gender: '女',
      totalRooms: 80,
      availableRooms: 12,
      floors: 4,
      facilities: ['空调', '热水器', 'WiFi']
    }
  ]
}

const loadApplicationStatus = async () => {
  // 模拟加载申请状态
  // applicationStatus.value = {
  //   type: 'pending',
  //   title: '申请审核中',
  //   message: '您的宿舍申请正在审核中，请耐心等待审核结果。',
  //   submittedAt: '2024-10-15T10:30:00'
  // }
}

const loadRooms = async (buildingId) => {
  // 模拟加载房间数据
  const roomsData = {
    1: [ // 1号楼房间
      { id: 101, number: '101', floor: 1, status: 'available', occupiedBeds: 0, totalBeds: 4, orientation: '南向', area: 20, facilities: ['阳台', '独卫'] },
      { id: 102, number: '102', floor: 1, status: 'partial', occupiedBeds: 2, totalBeds: 4, orientation: '北向', area: 20, facilities: ['阳台'] },
      { id: 103, number: '103', floor: 1, status: 'full', occupiedBeds: 4, totalBeds: 4, orientation: '南向', area: 20, facilities: ['阳台', '独卫'] },
      { id: 201, number: '201', floor: 2, status: 'available', occupiedBeds: 1, totalBeds: 4, orientation: '南向', area: 22, facilities: ['阳台', '独卫'] },
      { id: 202, number: '202', floor: 2, status: 'partial', occupiedBeds: 3, totalBeds: 4, orientation: '北向', area: 20, facilities: ['阳台'] },
      { id: 301, number: '301', floor: 3, status: 'available', occupiedBeds: 0, totalBeds: 4, orientation: '南向', area: 22, facilities: ['阳台', '独卫'] }
    ],
    2: [ // 2号楼房间
      { id: 201, number: '201', floor: 2, status: 'available', occupiedBeds: 0, totalBeds: 4, orientation: '东向', area: 18, facilities: ['阳台'] },
      { id: 202, number: '202', floor: 2, status: 'partial', occupiedBeds: 1, totalBeds: 4, orientation: '西向', area: 18, facilities: ['阳台'] },
      { id: 301, number: '301', floor: 3, status: 'available', occupiedBeds: 2, totalBeds: 4, orientation: '东向', area: 20, facilities: ['阳台', '独卫'] }
    ]
  }
  
  rooms.value = roomsData[buildingId] || []
}

const loadRoommates = async (roomId) => {
  // 模拟加载室友数据
  currentRoommates.value = [
    {
      id: 1,
      name: '李四',
      studentId: '2024002',
      major: '软件工程',
      grade: '2024级',
      hobbies: '阅读、音乐',
      avatar: null
    }
  ]
  
  availableRoommates.value = [
    {
      id: 2,
      name: '王五',
      studentId: '2024003',
      major: '计算机科学与技术',
      grade: '2024级',
      hobbies: '篮球、游戏',
      schedule: '早睡早起',
      avatar: null
    },
    {
      id: 3,
      name: '赵六',
      studentId: '2024004',
      major: '信息安全',
      grade: '2024级',
      hobbies: '电影、旅行',
      schedule: '夜猫子',
      avatar: null
    },
    {
      id: 4,
      name: '孙七',
      studentId: '2024005',
      major: '数据科学',
      grade: '2024级',
      hobbies: '健身、摄影',
      schedule: '规律作息',
      avatar: null
    }
  ]
}

const selectBuilding = (building) => {
  selectedBuilding.value = building
  selectedFloor.value = null
  selectedRoom.value = null
  loadRooms(building.id)
}

const getFloorRooms = (floor) => {
  return rooms.value.filter(room => room.floor === floor)
}

const selectRoom = (room) => {
  if (room.status === 'full') return
  selectedRoom.value = room
  loadRoommates(room.id)
}

const toggleRoommateSelection = (roommate) => {
  const index = selectedRoommates.value.indexOf(roommate.id)
  if (index > -1) {
    selectedRoommates.value.splice(index, 1)
  } else {
    // 检查是否超过房间容量
    const availableBeds = selectedRoom.value.totalBeds - selectedRoom.value.occupiedBeds - 1 // -1 for current user
    if (selectedRoommates.value.length < availableBeds) {
      selectedRoommates.value.push(roommate.id)
    } else {
      appStore.showNotification('房间床位不足', 'warning')
    }
  }
}

const nextStep = () => {
  if (canProceed.value) {
    currentStep.value++
  }
}

const submitApplication = async () => {
  if (!canSubmit.value) return
  
  try {
    // 模拟提交申请
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    applicationStatus.value = {
      type: 'pending',
      title: '申请提交成功',
      message: '您的宿舍申请已提交，请耐心等待审核结果。',
      submittedAt: new Date().toISOString()
    }
    
    // 重置表单
    currentStep.value = 1
    selectedBuilding.value = null
    selectedFloor.value = null
    selectedRoom.value = null
    selectedRoommates.value = []
    applicationNote.value = ''
    agreeTerms.value = false
    
    appStore.showNotification('申请提交成功', 'success')
  } catch (error) {
    appStore.showNotification('提交失败，请重试', 'error')
  }
}

const getStatusText = (status) => {
  const statusMap = {
    'available': '可入住',
    'partial': '部分空床',
    'full': '已满'
  }
  return statusMap[status] || status
}

const formatDateTime = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const getApplicationStatusText = (status) => {
  const statusMap = {
    'pending': '审核中',
    'approved': '已通过',
    'rejected': '已拒绝',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const showBuildingDetail = (building) => {
  selectedBuildingDetail.value = building
  showBuildingDetailModal.value = true
}

const loadApplicationHistory = async () => {
  // 模拟加载申请历史记录
  applicationHistory.value = [
    {
      id: 1,
      buildingName: '1号宿舍楼',
      roomNumber: '201',
      applicationType: '新申请',
      status: 'approved',
      submittedAt: '2024-09-15T10:30:00',
      note: '希望能分配到朝南的房间',
      approvedAt: '2024-09-16T14:20:00'
    },
    {
      id: 2,
      buildingName: '3号宿舍楼',
      roomNumber: '305',
      applicationType: '调换申请',
      status: 'rejected',
      submittedAt: '2024-10-01T09:15:00',
      note: '因为室友作息不合，希望调换房间',
      rejectReason: '当前学期不允许调换宿舍',
      rejectedAt: '2024-10-02T16:45:00'
    }
  ]
}

// 生命周期
onMounted(() => {
  loadBuildings()
  loadApplicationStatus()
  loadApplicationHistory()
})
</script>